package com.zzyl.intercept;

import cn.hutool.core.util.StrUtil;
import com.zzyl.constant.Constants;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.utils.UserThreadLocal;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class UserInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //如果不是映射到方法就放行，比如跨域验证请求、静态资源等不需要身份校验的请求
        // HandlerMethod 即controller对应的接口方法
        if(!(handler instanceof HandlerMethod)){
            return true;
        }

        //1、获取请求头中的token
        String token = request.getHeader(Constants.USER_TOKEN);
        log.info("用户登录的token令牌是：{}",token);
        if(StrUtil.isBlank(token)){
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }
        //2、校验令牌是否合法
        Claims claims = JwtUtil.parseJWT(
                jwtTokenManagerProperties.getBase64EncodedSecretKey(),
                token);

        //3、如果令牌合法，则放行，否则抛出异常
        if(ObjectUtil.isEmpty(claims)){
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }

        Object userId = claims.get(Constants.JWT_USERID);
        if(ObjectUtil.isEmpty(userId)){
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }
        UserThreadLocal.set(Long.parseLong(userId.toString()));
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //释放ThreadLocal中存储的用户id数据，避免内存溢出的风险
        UserThreadLocal.remove();
    }
}
